<template>
  <div class="list" ref="wrapper">
    <div>
      <!-- list页面热门城市部分 -->
       <div class="area">
        <div class="title border-topbottom">热门城市</div>
        <div class="button-list">
          <div
            class="button-wrapper"
            v-for="item of hot"
            :key="item.id"
            @click="handleCityClick(item.name)"
          >
            <div class="button">{{item.name}}</div>
          </div>
        </div>
      </div>

      <!-- list页面城市列表部分 遍历的cities是对象，item是对象里的数组，key是每一个数组的名字“A”，“B”... -->
      <div class="area" v-for="(item, key) of cities" :key="key"  :ref="key">
        <div class="title border-topbottom">{{key}}</div>
        <div class="item-list">
          <div
            class="item border-bottom"
            v-for="innerItem of item"
            :key="innerItem.id"
            @click="handleCityClick(innerItem.name)"
          >
            {{innerItem.name}}
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import Bscroll from 'better-scroll'
import {mapState, mapMutations} from 'vuex'
export default {
  name: 'CityList',
  props: {
    //接收 City.vue 传过来数据并在本页面进行遍历动态渲染页面
    hot: Array,
    cities: Object,
    letter: String
  },
  methods: {
    handleCityClick (city) {
      this.changeCity(city)
      this.$router.push('/home')
    },
    ...mapMutations(['changeCity'])
  },
  computed: {
    ...mapState(['city'])
  },
  mounted () {
    /* 创建一个better-scroll的实例，并传入一个dom元素指定需要滚动的区域 ,
    第二个参数是对象，配置是否能够点击，better-scroll里面的
    */
    this.scroll = new Bscroll(this.$refs.wrapper, {
      click: true
    })
  },
  watch: {
    letter () {
      if (this.letter) {
        //botter-scroll遍历中获取的都是数组，需要的是一个dom元素所以只需要数组的第一项即可
        const element = this.$refs[this.letter][0]
        console.log(element)
        this.scroll.scrollToElement(element)
      }
    }
  }
}
</script>

<style lang="less" scoped>
.border-topbottom {
  &:before {
    border-color: #ccc;
  }

  &:after {
    border-color: #ccc;
  }
}

.border-bottom {
  &:before {
    border-color: #ccc;
  }
}

.list {
  overflow: hidden;
  position: absolute;
  top: .84rem;
  left: 0;
  right: 0;
  bottom: 0;
  .title {
    line-height: .27rem;
    background: #eee;
    padding-left: 0.1rem;
    color: #333;
    font-size: .16rem;
  }

  .button-list {
    overflow: hidden;
    padding-left: .2rem;
    .button-wrapper {
      float: left;
      font-size: .14rem;
      background: #f1f1f1;
      width: .75rem;
      height: .3rem;
      margin: .075rem .04rem;
      .button {
        text-align: center;
        line-height: .3rem;
        border-radius: 0.03rem;
      }
    }
  }

  .item-list {
    .item {
      line-height: 0.38rem;
      padding-left: 0.1rem;
      font-size: .14rem;
      color: #333;
    }
  }
}
</style>
